package com.yklab.library.list.inter;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * 通用recyclerview加载更多监听器
 * <p>
 * Created by yukang on 2017/12/13.
 */

public abstract class EndRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    //用来标记是否正在向上滑动
    private boolean isSlidingUpward = false;
    private boolean isSlidingDownward = false;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        // 当不滑动时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            //获取最后一个完全显示的itemPosition
            int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
            int itemCount = manager.getItemCount();
            int firstItemPosition = manager.findFirstVisibleItemPosition();
            // 判断是否滑动到了最后一个item，并且是向上滑动
            if (lastItemPosition == (itemCount - 1) && isSlidingUpward) {
                //加载更多
                onLoadMore();
            } else if (firstItemPosition == 0 && isSlidingDownward) {
                onFirstItem();
            }

        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
        isSlidingUpward = dy > 0;
        isSlidingDownward = dy < 0;
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int firstItemPosition = manager.findFirstVisibleItemPosition();
        onScroll(firstItemPosition);
    }

    /**
     * 加载更多回调
     */
    public abstract void onLoadMore();

    /**
     * 滑动到第一条
     */
    public abstract void onFirstItem();

    /**
     * 记录滑动
     */
    public abstract void onScroll(int position);
}
